<template>
  <div class="container">
    <!-- 移动端菜单切换按钮 -->
    <div class="mobile-menu-toggle md:hidden">
      <el-button 
        type="primary" 
        circle 
        size="small"
        class="menu-toggle-btn"
        @click="toggleMobileMenu"
      >
        <el-icon><Menu /></el-icon>
      </el-button>
    </div>

    <!-- 头部：包含标题、添加/导出按钮 -->
    <div class="flex flex-wrap items-center justify-between mb-6 gap-3">
      <!-- 标题 -->
      <div>
        <h1 class="page-title text-2xl font-bold">ETC卡管理</h1>
        <p class="text-gray-500">管理所有ETC卡基本信息、余额和使用记录</p>
      </div>
      <!-- 添加/导出按钮 -->
      <div class="flex gap-2">
        <el-button type="primary" @click="openDialog()" class="btn-with-icon">
          <el-icon class="mr-1"><Plus /></el-icon>添加ETC卡
        </el-button>
        <el-button type="success" @click="exportData" class="btn-with-icon">
          <el-icon class="mr-1"><Download /></el-icon>导出数据
        </el-button>
      </div>
    </div>

    <!-- 搜索区域框 -->
    <el-card shadow="hover" class="mb-6 card-with-hover">
      <div class="search-container">
        <!-- 卡号搜索 -->
        <div class="search-item">
          <el-input
            v-model="searchForm.cardNumber"
            placeholder="请输入卡号"
            class="search-input"
            clearable
          >
            <template #prefix>
              <el-icon class="search-icon"><CreditCard /></el-icon>
            </template>
          </el-input>
        </div>
        
        <!-- 状态搜索 -->
        <div class="search-item">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            class="search-input"
            clearable
          >
            <el-option
              v-for="(label, value) in statusOptions"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </div>
        
        <!-- 操作按钮 -->
        <div class="search-actions">
          <el-button type="primary" @click="handleSearch" class="search-btn">
            <el-icon class="mr-1"><Search /></el-icon>查询
          </el-button>
          
          <el-button @click="resetSearch" class="reset-btn" type="info" plain>
            <el-icon class="mr-1"><Refresh /></el-icon>重置
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover" class="overflow-hidden card-with-hover">
      <el-table
        v-loading="loading"
        :data="filteredCards"
        border
        stripe
        style="width: 100%"
        :header-cell-class-name="'bg-gray-100 dark:bg-gray-700'"
        class="custom-table"
        fit
        @sort-change="handleSortChange"
      >
        <!-- 固定列 -->
        <el-table-column prop="id" label="ID" width="80" align="center" sortable="custom" fixed="left" />
        <el-table-column prop="cardNumber" label="卡号" min-width="150" sortable="custom" fixed="left" />
        
        <!-- 中等屏幕及以上显示的列 -->
        <el-table-column prop="balance" label="余额(元)" min-width="120" sortable="custom" class-name="hide-on-mobile">
          <template #default="{ row }">
            <span :class="Number(row.balance) < 100 ? 'text-red-500' : 'text-green-500'">{{ Number(row.balance).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="issueDate" label="发卡日期" min-width="120" sortable="custom" class-name="hide-on-mobile" />
        <el-table-column prop="expiryDate" label="有效期" min-width="120" sortable="custom" class-name="hide-on-mobile" />
        <el-table-column prop="status" label="状态" min-width="100" sortable="custom" class-name="hide-on-mobile">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        
        <!-- 操作列 -->
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="small"
                circle
                @click="editCard(scope.row)"
                class="edit-btn"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button 
                type="danger" 
                size="small"
                circle
                @click="deleteCard(scope.row)"
                class="delete-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container mt-4 flex justify-center">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="DEFAULT_PAGE_SIZES"
          :total="totalCards"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="custom-pagination"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑ETC卡' : '添加ETC卡'"
      width="500px"
      destroy-on-close
      class="custom-dialog"
    >
      <el-form
        ref="formRef"
        :model="cardForm"
        :rules="rules"
        label-width="100px"
        label-position="right"
        class="form-container"
      >
        <el-form-item label="卡号" prop="cardNumber">
          <el-input v-model="cardForm.cardNumber" placeholder="请输入卡号" />
        </el-form-item>
        <el-form-item label="卡密码" prop="password" v-if="!isEdit">
          <el-input v-model="cardForm.password" placeholder="请输入卡密码" show-password />
        </el-form-item>
        <el-form-item label="初始余额" prop="balance" v-if="!isEdit">
          <el-input-number v-model="cardForm.balance" :min="0" :precision="2" :step="100" style="width: 100%" />
        </el-form-item>
        <el-form-item label="发卡日期" prop="issueDate">
          <el-date-picker 
            v-model="cardForm.issueDate" 
            type="date" 
            placeholder="选择发卡日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="有效期" prop="expiryDate">
          <el-date-picker 
            v-model="cardForm.expiryDate" 
            type="date" 
            placeholder="选择有效期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="cardForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option
              v-for="(label, value) in statusOptions"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="cardForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Search, Refresh, Edit, Delete, Menu, CreditCard } from '@element-plus/icons-vue'
import { etcCardApi } from '@/api'

export default {
  name: 'EtcCards',
  setup() {
    // 常量
    const DEFAULT_PAGE_SIZES = [10, 20, 50, 100]
    const statusOptions = {
      1: '正常',
      2: '挂失',
      3: '冻结',
      4: '注销'
    }
    
    // 表单相关
    const formRef = ref(null)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const cardForm = reactive({
      id: null,
      cardNumber: '',
      balance: 0,
      issueDate: '',
      expiryDate: '',
      status: 1,
      remark: ''
    })
    
    // 搜索相关
    const searchForm = reactive({
      cardNumber: '',
      status: ''
    })

    // 表格相关
    const loading = ref(false)
    const cards = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalCards = ref(0)
    const sortBy = ref('id')
    const sortOrder = ref('descending')

    // 验证规则
    const rules = {
      cardNumber: [
        { required: true, message: '请输入卡号', trigger: 'blur' },
        { min: 7, max: 10, message: '卡号长度应为7-10个字符', trigger: 'blur' }
      ],
      balance: [
        { required: true, message: '请输入余额', trigger: 'blur' },
        { type: 'number', min: 0, message: '余额不能为负数', trigger: 'blur' }
      ],
      issueDate: [
        { required: true, message: '请选择发卡日期', trigger: 'change' }
      ],
      expiryDate: [
        { required: true, message: '请选择有效期', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }

    // 计算属性
    const filteredCards = computed(() => {
      return cards.value.map(card => {
        // 处理状态显示
        if (card.status !== undefined) {
          card.statusText = getStatusLabel(card.status);
          card.statusType = getStatusType(card.status);
        } else {
          // 默认为正常状态
          card.statusText = '正常';
          card.statusType = 'success';
          card.status = 1;
        }
        
        // 确保余额显示正确
        if (card.balance === undefined || card.balance === null) {
          card.balance = 0;
        }
        
        // 确保日期格式正确
        if (!card.issueDate || card.issueDate === 'undefined') {
          card.issueDate = '';
        }
        
        if (!card.expiryDate || card.expiryDate === 'undefined') {
          card.expiryDate = '';
        }
        
        return card;
      });
    })

    // 方法
    const loadCards = async () => {
      loading.value = true
      try {
        // 构造API请求参数
        const params = {
          current: currentPage.value,
          size: pageSize.value,
          searchTerm: searchForm.cardNumber || null,
          status: searchForm.status || null
        }
        
        // 调用etcCardApi的getEtcCardList方法
        const page = await etcCardApi.getEtcCardList(params)
        
        // 解析返回的数据
        if (page && page.records) {
          // 处理每条记录的数据格式
          const processedRecords = page.records.map(card => {
            // 确保status是数字
            if (card.status !== undefined) {
              card.status = Number(card.status);
            } else {
              card.status = 1; // 默认为正常状态
            }
            
            // 确保balance是数字
            if (card.balance !== undefined) {
              card.balance = Number(card.balance);
            } else {
              card.balance = 0;
            }
            
            // 处理日期格式
            const currentDate = new Date();
            const formattedCurrentDate = formatDate(currentDate);
            
            if (!card.issueDate || card.issueDate === 'undefined') {
              // 尝试使用createTime或其他日期字段
              if (card.createTime) {
                card.issueDate = formatDate(card.createTime);
              } else {
                card.issueDate = formattedCurrentDate;
              }
            }
            
            if (!card.expiryDate || card.expiryDate === 'undefined') {
              // 如果有issueDate，则设置为issueDate后5年
              if (card.issueDate) {
                try {
                  const date = new Date(card.issueDate);
                  date.setFullYear(date.getFullYear() + 5);
                  card.expiryDate = formatDate(date);
                } catch (e) {
                  const futureDate = new Date(currentDate);
                  futureDate.setFullYear(futureDate.getFullYear() + 5);
                  card.expiryDate = formatDate(futureDate);
                }
              } else {
                const futureDate = new Date(currentDate);
                futureDate.setFullYear(futureDate.getFullYear() + 5);
                card.expiryDate = formatDate(futureDate);
              }
            }
            
            // 确保备注不为空
            card.remark = card.remark || '';
            
            return card;
          });
          
          cards.value = processedRecords;
          totalCards.value = page.total || 0;
          console.log('ETC卡数据加载成功:', cards.value.length, '条记录')
        } else {
          cards.value = []
          totalCards.value = 0
          console.warn('返回的ETC卡数据格式不正确:', page)
        }
      } catch (error) {
        console.error('加载ETC卡数据失败:', error)
        ElMessage.error('加载数据失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
      loadCards()
    }

    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      handleSearch()
    }

    const handleSortChange = ({ prop, order }) => {
      if (prop) {
        sortBy.value = prop
        sortOrder.value = order
        loadCards()
      }
    }

    const handleSizeChange = (size) => {
      pageSize.value = size
      loadCards()
    }

    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadCards()
    }

    const openDialog = (isEditMode = false) => {
      isEdit.value = isEditMode
      dialogVisible.value = true
      
      // 加载可用车辆
      if (!isEditMode) {
        // 新增模式，重置表单
        Object.keys(cardForm).forEach(key => {
          if (key === 'status') {
            cardForm[key] = 1
          } else if (key === 'balance') {
            cardForm[key] = 0
          } else if (key !== 'id') {
            cardForm[key] = ''
          }
        })
        
        // 设置默认日期
        const now = new Date()
        cardForm.issueDate = now.toISOString().split('T')[0]
        // 默认有效期为5年后
        const expiryDate = new Date()
        expiryDate.setFullYear(expiryDate.getFullYear() + 5)
        cardForm.expiryDate = expiryDate.toISOString().split('T')[0]
      }
    }

    const editCard = (row) => {
      // 编辑模式，复制数据到表单
      Object.keys(cardForm).forEach(key => {
        if (row[key] !== undefined) {
          cardForm[key] = row[key]
        }
      })
      openDialog(true)
    }

    const deleteCard = (row) => {
      ElMessageBox.confirm(
        `确认删除ETC卡 ${row.cardNumber} 的记录吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          loading.value = true
          // 调用etcCardApi的deleteEtcCard方法
          await etcCardApi.deleteEtcCard(row.id)
          ElMessage.success('删除成功')
          loadCards() // 重新加载列表
        } catch (error) {
          console.error('删除ETC卡失败:', error)
          ElMessage.error('删除失败，请稍后重试')
        } finally {
          loading.value = false
        }
      }).catch(() => {
        // 用户取消删除
      })
    }

    const submitForm = () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            loading.value = true
            
            // 确保表单数据完整性
            if (!cardForm.status) {
              cardForm.status = 1; // 默认为正常状态
            }
            
            if (isEdit.value) {
              // 编辑模式，调用updateEtcCard方法
              await etcCardApi.updateEtcCard(cardForm)
              ElMessage.success('更新成功')
            } else {
              // 新增模式，调用addEtcCard方法
              await etcCardApi.addEtcCard(cardForm)
              ElMessage.success('添加成功')
            }
            dialogVisible.value = false
            loadCards() // 重新加载列表
          } catch (error) {
            console.error('提交表单失败:', error)
            ElMessage.error('操作失败，请稍后重试')
          } finally {
            loading.value = false
          }
        }
      })
    }

    const exportData = async () => {
      try {
        loading.value = true
        ElMessage.info('正在导出数据，请稍候...')
        
        // 构建导出参数，使用当前的筛选条件
        const params = {
          searchTerm: searchForm.cardNumber || null,
          status: searchForm.status || null
        }
        
        // 调用API获取导出数据
        const response = await etcCardApi.exportEtcCards(params)
        
        // 创建Blob对象
        const blob = new Blob([response.data], { 
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        })
        
        // 创建下载链接并触发下载
        const link = document.createElement('a')
        const fileName = `etc_cards_export_${new Date().toISOString().split('T')[0]}.xlsx`
        
        // 创建URL并设置下载属性
        const url = window.URL.createObjectURL(blob)
        link.href = url
        link.download = fileName
        
        // 将链接添加到页面并触发点击
        document.body.appendChild(link)
        link.click()
        
        // 清理
        window.URL.revokeObjectURL(url)
        document.body.removeChild(link)
        
        ElMessage.success('数据导出成功')
        loading.value = false
      } catch (error) {
        console.error('导出数据失败:', error)
        ElMessage.error('导出失败，请稍后重试')
        loading.value = false
      }
    }

    const getStatusLabel = (status) => {
      // 确保状态是数字
      const statusNum = Number(status);
      return statusOptions[statusNum] || '未知状态';
    }

    const getStatusType = (status) => {
      // 确保状态是数字
      const statusNum = Number(status);
      const types = {
        1: 'success',
        2: 'warning',
        3: 'danger',
        4: 'info'
      }
      return types[statusNum] || 'info';
    }

    const toggleMobileMenu = () => {
      // 控制移动端菜单显示
      const event = new CustomEvent('toggle-sidebar')
      window.dispatchEvent(event)
    }

    // 添加日期格式化函数
    const formatDate = (date) => {
      if (!date) return '';
      
      if (typeof date === 'string') {
        // 如果是ISO格式的日期字符串，只取日期部分
        if (date.includes('T')) {
          return date.split('T')[0];
        }
        return date;
      }
      
      if (date instanceof Date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
      
      return '';
    };

    // 初始化
    onMounted(() => {
      loadCards()
    })

    return {
      DEFAULT_PAGE_SIZES,
      statusOptions,
      formRef,
      dialogVisible,
      isEdit,
      cardForm,
      searchForm,
      loading,
      cards,
      currentPage,
      pageSize,
      totalCards,
      filteredCards,
      rules,
      loadCards,
      handleSearch,
      resetSearch,
      handleSortChange,
      handleSizeChange,
      handleCurrentChange,
      openDialog,
      editCard,
      deleteCard,
      submitForm,
      getStatusLabel,
      getStatusType,
      toggleMobileMenu,
      exportData
    }
  }
}
</script>

<style scoped>
.container {
  padding: 1rem;
  position: relative;
}

.search-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.search-item {
  flex: 1;
  min-width: 200px;
}

.search-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.mobile-menu-toggle {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
}

@media (max-width: 768px) {
  .hide-on-mobile {
    display: none;
  }
  
  .search-item {
    min-width: 100%;
  }
  
  .search-actions {
    width: 100%;
    margin-top: 12px;
    justify-content: center;
  }
}
</style> 